import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/bloc/FileBrowseCubit.dart';
import 'package:im_app/im/page/bloc/MessageSendCubit.dart';
import 'package:im_app/im/page/bloc/SelectGroupUsersCubit.dart';
import 'package:im_app/im/page/bloc/WebRtcCubit.dart';
import 'package:im_app/im/page/sub/WebRtcVideoPage.dart';
import 'package:im_app/im/util/HexColor.dart';
import 'package:im_app/im/util/ImCacheFactory.dart';
import 'package:im_app/im/util/ImConstant.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:im_app/im/util/UiUtil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../dao/ImSessionDao.dart';
import '../../../pojo/ImPojo.dart';
import '../../../util/PermissionUtil.dart';
import '../../bloc/CollectSelectCubit.dart';
import '../../sub/CaptureImagePage.dart';
import '../../sub/CollectSelectPage.dart';
import '../../sub/FileBrowsePage.dart';
import '../../sub/SelectGroupUsersPage.dart';
import 'LButton.dart';
import 'UiUtil.dart';
import 'dialog/VideoAndAudioBottomSheet.dart';

class MessageSendPlusView extends StatefulWidget {

  final int sessionId;

  const MessageSendPlusView({ required this.sessionId, super.key});

  @override
  State<StatefulWidget> createState() => _MessageSendPlusState();
}

class _MessageSendPlusState extends State<MessageSendPlusView> {
  late PageController _pageController;
  var _selectIndex = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
          child: PageView(
            controller: _pageController,
            children: [_buildPageViewOne(context)],
            onPageChanged: _onItemTapped,
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () {
                _pageController.jumpToPage(0);
              },
              child: Dot(
                isActive: _selectIndex == 0,
              ),
            ),
            // GestureDetector(
            //   onTap: () {
            //     _pageController.jumpToPage(1);
            //   },
            //   child: Dot(
            //     isActive: _selectIndex == 1,
            //   ),
            // ),
          ],
        )
      ],
    );
  }

  Widget _buildPageViewOne(BuildContext context) {
    return GridView(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4, childAspectRatio: 0.84),
      children: <Widget>[
        LButton(
          name: '相册',
          assetImage: 'assets/svg/image.svg',
          selectCallback: ()=>_selectImage(context),
        ),
        LButton(
          name: '拍摄',
          assetImage: 'assets/webrtc-img/camera.svg',
          selectCallback: ()=> _captureImage(context),
        ),
        LButton(
          name: '视频通话',
          assetImage: 'assets/svg/video.svg',
          selectCallback: ()=> _video(context),
        ),
        // LButton(
        //   name: '位置',
        //   assetImage: 'assets/svg/position.svg',
        //   selectCallback: () {},
        // ),
        // LButton(
        //   name: '红包',
        //   assetImage: 'assets/svg/redbag.svg',
        //   selectCallback: () {},
        // ),
        // LButton(
        //   name: '转账',
        //   assetImage: 'assets/svg/transferMoney.svg',
        //   selectCallback: () {},
        // ),
        LButton(
          name: '文件',
          assetImage: 'assets/svg/directory.svg',
          selectCallback: () { _selectFile(context); },
        ),
        // LButton(
        //   name: '语音通信',
        //   assetImage: 'assets/svg/voice.svg',
        //   selectCallback: () {},
        // ),
        LButton(
          name: '我的收藏',
          assetImage: 'assets/svg/mycollect.svg',
          selectCallback: ()=> _selectCollect(context),
        ),
      ],
    );
  }

  Widget _buildPageViewTwo(BuildContext context) {
    return GridView(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4, childAspectRatio: 1),
      children: <Widget>[
        LButton(
          name: '名片',
          assetImage: 'assets/svg/personCard.svg',
          selectCallback: () {},
        ),
        LButton(
          name: '文件',
          assetImage: 'assets/svg/directory.svg',
          selectCallback: () { _selectFile(context); },
        ),
        LButton(
          name: '音乐',
          assetImage: 'assets/svg/music.svg',
          selectCallback: () {  },
        ),
      ],
    );
  }

  // 选择照片
  void _selectImage(BuildContext context) async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null && context.mounted) {
      MessageSendCubit messageSendCubit = context.read<MessageSendCubit>();
      messageSendCubit.add(MessageSendSendMessageEvent(image.path, ImMessageType.Image));
    }
  }

  // 拍照
  void _captureImage(BuildContext context) async {
    // 请求相机权限
    var isGranted = await PermissionUtil.getPermissionStatus(Permission.camera);
    if (isGranted) {
      if (ImSingleton.getInstance().cameras.isEmpty) {
        ImSingleton.getInstance().cameras = await availableCameras();
      }
      if (context.mounted) {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (BuildContext context) {
              return const CaptureImagePage();
            }));
      }
    }
  }

  // 视频通话
  void _video(BuildContext context) async {
    var sessionDao = ImSessionDao();
    var session = await sessionDao.getById(widget.sessionId);

    if (session?.groupCode == null && session!.fromUserId! == session.toUserId!) {
      UiUtil.showSnackBar(context, '不能向自己发起视频聊天');
      return;
    }

    showVideoAndAudioBottomSheet(context, session!);
  }

  // 选择附件
  void _selectFile(BuildContext context) async {
    // FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
    // if (result != null) {
    //   List<String> files = result.paths.map((path) => path!).toList();
    //   MessageSendCubit messageSendCubit = context.read<MessageSendCubit>();
    //   messageSendCubit.add(MessageSendSendMessagesEvent(files, ImMessageType.File));
    // }
    var sessionDao = ImSessionDao();
    var session = await sessionDao.getById(widget.sessionId);

    if (context.mounted) {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (BuildContext context) {
            return BlocProvider(
              create: (context) => FileBrowseCubit(session!),
              child: const FileBrowsePage(),
            );
          },
          settings: const RouteSettings(name: '/FileBrowsePage'))
      );
    }
  }

  // 选择收藏
  void _selectCollect(BuildContext context) async {
    var sessionDao = ImSessionDao();
    var session = await sessionDao.getById(widget.sessionId);
    if (context.mounted) {
      Navigator.of(context).push(MaterialPageRoute(
          builder: (BuildContext context) {
            return BlocProvider(
              create: (context) => CollectSelectCubit(session!)..loadData(),
              child: const CollectSelectPage(),
            );
          },
          settings: const RouteSettings(name: '/CollectSelectPage'))
      );
    }
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectIndex = index;
    });
  }
}

class Dot extends StatelessWidget {
  final bool isActive;

  const Dot({this.isActive = false, Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 15,
      height: 15,
      margin: const EdgeInsets.only(left: 5, right: 5, bottom: 10),
      decoration: BoxDecoration(
        color: isActive ? Colors.red : Colors.grey,
        shape: BoxShape.circle,
      ),
    );
  }
}
